﻿
using Microsoft.AspNetCore.Mvc.Internal;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;


namespace ThinNet.WebApi
{
    public static class MvcServiceCollectionExtensions
    {
        public static IMvcBuilder AddWebApi(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException("services");
            }

            var mvcCoreBuilder = services.AddMvcCore();
            //全局配置Json序列化处理
            mvcCoreBuilder.AddJsonOptions(options => {
                //忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //忽略null值
                options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                //首字母小写
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            });
            mvcCoreBuilder.AddAuthorization();
            mvcCoreBuilder.AddFormatterMappings();
            mvcCoreBuilder.AddDataAnnotations();
            mvcCoreBuilder.AddJsonFormatters();

            mvcCoreBuilder.AddCors();
            return new MvcBuilder(mvcCoreBuilder.Services, mvcCoreBuilder.PartManager);
        }
    }
}
